<template>
    <div id="SlideBar" class="SlideBar" ref="testwidth">
        <div class="item" ref="slide" :style="slideStyle" @touchstart="start($event)" @touchmove="move($event)" @touchend="end($event)">
          <slot></slot>
        </div>
    </div>
</template>
<script>
    export default {
        name: 'SlideBar',
        props: {
            slideWidth:Number
        },
        data (){
            return {
                flag: false,
                startX: 0,
                endX: 0,
                slideStyle: {
                    left: 0,
                    top:0,
                    transition: 'none'
                }
            }
        },
        methods: {
            start (e){  //记录开始滑动屏幕的X轴的位置
                this.flag = true;
                this.startX = e.touches[0].clientX;
                this.endX = this.$refs.slide.offsetLeft;
                this.slideStyle.transition = 'none';             
                this.widthss =this.$refs.slide.offsetWidth
            },
            move (e){
                if(this.flag){
                    // 处理鼠标移动的逻辑
                    var moveX = this.endX + (e.touches[0].clientX - this.startX);  //计算滑动的距离
                    let lengs =  this.widthss -  this.cientsWidth
                    if( moveX>-lengs && moveX<0){
                        this.slideStyle.left = moveX + 'px'; 
                    }else if(moveX<-lengs){
                        this.slideStyle.left =-lengs + 'px'; 
                    }else if(moveX>0){
                        this.slideStyle.left =0 + 'px'; 
                    }
                    
                }
            },
            end (e){
                if(this.flag){
                    this.flag = false;
                    var moveX = e.changedTouches[0].clientX - this.startX;  //计算滑动的距离
                    this.slideStyle.transition = 'left 0.5s';
                }
            }
        },
        mounted (){
            var _this = this;
            // 使用js的现代事件监听transition过渡结束
            this.$refs.slide.addEventListener('transitionend',function(){
                _this.endX = this.offsetLeft;
            })
            this.cientsWidth = this.$refs.testwidth.offsetWidth
        }
    }
</script>

<style>
.SlideBar{
    position:relative;
    width: 100%;
    height: auto;
}


.item{
  position: absolute;
  z-index: 2;
  width: auto;
  height: auto;
}

</style>
